import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/pages/specialtopic/controller/special_topic_ctr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';

import '../../../components/base/base_nav_bar.dart';
import '../../../components/base/base_page.dart';
import '../../../routes/routes.dart';
import '../../../utils/ThemeConfig.dart';
import '../../goods/binding/goods_detail_binding.dart';
import '../../goods/view/goods_detail_page.dart';
import '../entity/special_topic_commodity_entity.dart';

class SpecialTopicPage extends GetView<SpecialTopicCtr> {
  const SpecialTopicPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SpecialTopicCtr>(builder: (controller) {
      return BasePage(
        title: controller.data != null ? controller.data!.name : '专题商品',
        iconType: IconType.back,
        isShowPadding: true,
        refreshController: controller.baseRefreshCtr,
        enablePullDown: true,
        enablePullUp: controller.hasNextPage,
        onPageRefresh: controller.onPageRefresh,
        onPageLoading: controller.onPageLoading,
        isShowShare: true,
        shareCallBack: () {
          controller.sharePage();
        },
        children: [
          if (controller.data != null) ...[
            BaseImage(
              url: controller.data!.fileUrl!,
              width: ScreenUtil().screenWidth,
              fit: BoxFit.cover,
            )
          ],
          Container(
            margin: EdgeInsets.only(top: 10.w),
            child: MasonryGridView.builder(
              shrinkWrap: true, // 开启动态高度计算
              physics: const NeverScrollableScrollPhysics(), // 禁止 GridView 滚动
              itemCount: controller.list.length,
              mainAxisSpacing: 8.0, // 主轴（垂直方向）间距
              crossAxisSpacing: 8.0, // // 根据你的数据更新这个数量
              gridDelegate: const SliverSimpleGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2, // 设置列数
              ),
              itemBuilder: (context, index) {
                final item = controller.list[index];
                return _createGoodItem(item); // 根据索引创建商品项
              },
            ),
          )
        ],
      );
    });
  }

  Widget _createGoodItem(SpecialTopicCommodityDataGoodsListList item) {
    return InkWell(
      onTap: () {
        final id = item.commodityId;
        if (id != null) {
          Get.to(
            () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
            routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
            arguments: {"id": id}, // 传递其它参数
            binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
          );
        }
      },
      child: Container(
        // margin: const EdgeInsets.all(8),
        width: 175.w, // 如果想保持宽度一致
        decoration: BoxDecoration(
          color: Colors.white, // 设置背景颜色为白色
          borderRadius: BorderRadius.circular(10), // 设置圆角
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1), // 添加阴影颜色
              blurRadius: 5, // 阴影模糊程度
              offset: const Offset(0, 2), // 阴影偏移
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: const BorderRadius.vertical(top: Radius.circular(10)), // 上方圆角
              child: BaseImage(
                url: item.mainImage!,
                fit: BoxFit.cover, // 裁剪方式
              ),
            ), // 图片占用固定高度
            SizedBox(height: 8.w), // 间距
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: RichText(
                text: TextSpan(
                  children: [
                    WidgetSpan(
                      alignment: PlaceholderAlignment.middle, // 垂直居中对齐
                      child: goodsTypeTag(
                        getGoodsTypeName(item.commodityType!),
                        margin: const EdgeInsets.only(right: 5), // 设置右边距
                      ),
                    ),
                    TextSpan(
                      text: item.commodityName!,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w400,
                        color: Tools.fromHex('#3D3D3D'),
                      ),
                    ),
                  ],
                ),
                maxLines: 2, // 设置最大行数为 2
                overflow: TextOverflow.ellipsis, // 超过部分显示省略号
              ),
            ),

            Container(
              padding: const EdgeInsets.only(left: 8, right: 8),
              child: Wrap(
                runSpacing: 5.w,
                children: [
                  for (var text in item.discountLabel!)
                    BorderedText(
                      text: text,
                      padding: const EdgeInsets.only(left: 2, right: 2, top: 2, bottom: 2),
                      borderColor: ThemeConfig.themeColor,
                      textStyle: const TextStyle(fontSize: 11, color: ThemeConfig.themeColor),
                    ),
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.all(8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  RichText(
                    text: TextSpan(children: [
                      TextSpan(
                        text: '¥',
                        style: TextStyle(
                          color: Tools.fromHex('#F83F2D'),
                          fontWeight: FontWeight.w700,
                          fontSize: 10,
                        ),
                      ),
                      TextSpan(
                        text: item.priceCost!.toString(),
                        style: TextStyle(
                          color: Tools.fromHex('#F83F2D'),
                          fontWeight: FontWeight.w700,
                          fontSize: 15,
                        ),
                      ),
                      const WidgetSpan(
                        child: SizedBox(width: 10), // 插入一个 10 像素的空白
                      ),
                    ]),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget createGoodsTypeTag(SpecialTopicCommodityDataGoodsListList item) {
    return goodsTypeTag(
      getGoodsTypeName(item.commodityType!),
      margin: const EdgeInsets.only(right: 5), // 设置右边距
    );
  }
}
